package com.wx.bootsecurity.config;

import com.wx.bootsecurity.handler.MyAccessDenidHandler;
import com.wx.bootsecurity.handler.RestAuthenticationEntryPoint;
import com.wx.bootsecurity.service.impl.CustemUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

/**
 * @Author: aerfazhe
 * @Date: 2021/7/21 18:54
 * @Statement: Security配置类
 */
@EnableGlobalMethodSecurity(prePostEnabled = true) // 会开启相关注解
@Configuration
@EnableWebSecurity //启动Spring Securiry
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private MyAccessDenidHandler myAccessDenidHandler;

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;

    @Autowired
    private CustemUserDetailsService custemUserDetailsService;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private PersistentTokenRepository persistentTokenRepository;

    /**
     * 自定义登录页面
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //设置不拦截页面，可直接通过，路径访问 "/", "/index", "/home" 则不拦截
        http.authorizeRequests()
                //静态资源和一些所有人都能访问的请求
                .antMatchers("/css/**","/staic/**", "/js/**","/images/**").permitAll()
                .antMatchers("/","/user/tologin", "/showLogin","toError").permitAll()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .anyRequest().authenticated()// 所有请求必须登录后才可以访问
                .and()
                .userDetailsService(userDetailsService);
//        结合access自定义权限访问控制
//                .anyRequest().access("@myServiceImpl.hasPermission(httpServletRequest,authentication)");
//        自定义登录和登出页面
/*        http.formLogin() //表单认证或表单提交
                .loginPage("/showLogin") //自定义登录页面
//                成功后跳转的页面
                .successForwardUrl("/main")
//                登录失败后跳转的页面
                .failureForwardUrl("/toError")
                .permitAll()
                .and()
                .logout()
                .logoutSuccessUrl("/showLogin")
                .permitAll();*/

//        关闭csrf防护 防止使用自定义登录请求不进入UserDetailsService的loadUserByUsername(String username)方法
        http.csrf().disable();

//        登录拦截过滤器token
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

//        异常处理403
        http.exceptionHandling()
                .accessDeniedHandler(myAccessDenidHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint);

//        记住我
        http.rememberMe()
//                生效时间 秒
                .tokenValiditySeconds(60)
//                自定义登录逻辑
                .userDetailsService(custemUserDetailsService)
//                持久层对象
                .tokenRepository(persistentTokenRepository);

    }

    /**
     * 注入加密
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 记住我
     * @return
     */
    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
//      自动建表，第一次启动需要，第二次启动注释掉
//        jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }

}
